//
//  HSLTabBar.swift
//  HSLMicroBlog
//
//  Created by mac on 15/12/12.
//  Copyright © 2015年 HSL. All rights reserved.
//

import UIKit

class HSLTabBar: UITabBar {

    //定义撰写按钮点击的回调闭包
    var composeBtnClosure: (()->())?
    
    // MARK: - 设置UI
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    func setupUI() {
        //设置背景
        self.backgroundImage = UIImage(named: "tabbar_background")
        //添加撰写按钮
        addSubview(composeButton)
    }
    
    //布局
    override func layoutSubviews() {
        super.layoutSubviews()
        composeButton.center = CGPoint(x: self.frame.width * 0.5, y: self.frame.height * 0.5)
        
        let childW = self.frame.width / 5
        var index = 0
        //调整按钮位置
        for childView in subviews {
            if childView.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                childView.frame = CGRect(x: CGFloat(index) * childW, y: 0, width: childW, height: self.frame.height)
                index++
            }
            if index == 2 {
                index++
            }
        }
        
    }
    
    // MARK: - 监听事件
    
    @objc private func composeBtnDidClick() {
        print("点击撰写按钮")
        composeBtnClosure?()
    }
    
    // MARK: - 懒加载控件
    
    //撰写按钮
    lazy var composeButton: UIButton = {
        let button = UIButton()
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        //设置加号图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        //设置大小
        button.sizeToFit()
        //添加点击事件
        button.addTarget(self, action: "composeBtnDidClick", forControlEvents: .TouchUpInside)
        return button
    }()
    

}
